package com.guiassysdesigners.webapp.action;

import java.io.IOException;
import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Request;

import org.apache.commons.digester.SetRootRule;
import org.springframework.security.access.AccessDeniedException;

import com.guiassysdesigners.model.Suggestion;
import com.guiassysdesigners.service.FormValidationException;
import com.guiassysdesigners.service.SuggestionManager;
import com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.Param;

/**
 * JSF Page class to handle editing a suggestion with a form.
 * 
 * @author guiassys
 */
public class SuggestionForm extends BasePage implements Serializable {
	private static final long serialVersionUID = -483900620559038435L;

	private String id;
	private Suggestion suggestion = new Suggestion();
	private SuggestionManager suggestionManager;
	
	public void setId(String id){
		this.id = id;
	}

	public Suggestion getSuggestion() {
		return suggestion;
	}

	public void setSuggestion(Suggestion suggestion) {
		this.suggestion = suggestion;
	}

	public void setSuggestionManager(SuggestionManager suggestionManager) {
		this.suggestionManager = suggestionManager;
	}

	public String save() throws IOException {
		try {
			suggestion = suggestionManager.saveSuggestion(suggestion);
			if(null != suggestion.getId()){
				addMessage("success.suggestion.added");		
			}
		} catch (AccessDeniedException ade) {
			log.warn(ade.getMessage());
			getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
			return null;
		} catch (FormValidationException e){
			log.warn(e.getMessage());
			addError(e.getMessage(), getText(e.getArg()));
			return null;
		}
		return "mainMenu";
	}
	
    public String cancel() {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'cancel' method");
        }

        return "mainMenu";
    }

    public String add(){
    	return "addSuggestionForm";
    }
    
    public String edit() {
        // if a suggestion's id is passed in
        if (id != null && !"".equals(id)) {
            log.debug("Editing suggestion, id is: " + id);
            suggestion = suggestionManager.getSuggestion(id);
        }
        return "editSuggestion";
    }
    
    public String delete() {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'delete' method");
        }
        
        if(null != suggestion.getId()){
        	suggestionManager.remove(suggestion);
        	addMessage("success.suggestion.deleted");
        }

        return "mainMenu";
    }

}
